import { useLoginStore } from './../stores/modules/login'
import { useUserStore } from '@/stores'
import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'

NProgress.configure({
  showSpinner: false
})
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/home/index.vue')
    },
    {
      path: '/training/:trainingId',
      name: 'Training',
      component: () => import('@/views/training/index.vue'),
      props: true
    },
    {
      path: '/:catchAll(.*)',
      name: '404',
      component: () => import('@/views/not-found/index.vue')
    }
  ]
})

router.beforeEach(async (to, from) => {
  NProgress.start()
  const loginStore = useLoginStore()
  const userStore = useUserStore()
  if (to.path != '/login') {

    if (!loginStore.token) {
      return `/login?returnUrl=${to.fullPath}`
    }
    if (!userStore.user) {
      await userStore.getProfile()
      return to.path
    }
  } else if (loginStore.token) {
    await userStore.getProfile()
    return from.path
  }
})
router.afterEach(() => {
  NProgress.done()
})
export default router
